<template>
  <div  style="margin-left: 5px;margin-right: 5px">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="default" icon="el-icon-refresh" size="mini" @click="getList">刷新</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5" style="line-height: 29px;font-size: 16px;color: #FFFFFF;">  碳排放量：（{{carbonNum}}）
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="productCarbonConsumablesList" @selection-change="handleSelectionChange" border height="580px">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="50" />
      <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true"/>
      <el-table-column label="排放因子值" align="center" prop="factorNum"  :show-overflow-tooltip="true"/>
      <el-table-column label="数量" align="center" prop="quantity" :show-overflow-tooltip="true"/>

      <el-table-column label="碳排放量" align="center"  :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{scope.row.factorNum&&scope.row.quantity?(scope.row.factorNum*scope.row.quantity).toFixed(2):0}}
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="factorUnit" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)" v-hasPermi="['carbon:productCarbonConsumables:edit']">修改</el-button>
          <el-button size="mini" type="text" @click="handleShowHis(scope.row)" v-hasPermi="['carbon:productCarbonConsumables:edit']">减排路径</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 添加或修改产品碳足迹-产品排放行为记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body custom-class="show-back-class">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="环节" prop="stageId">
          <el-select v-model="form.stageId" placeholder="请选择环节" style="width: 100%">
            <el-option class="index-option" v-for="dict in stageOptions"
                       :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="因子特征" prop="categorizeCode">
          <el-cascader  v-model="categorizeCodeArr" style="width: 100%" @change="chickCategorizeCode"
                        :options="$store.state.factorDict.categorizeTreeDict1"
                        :props="{value:'idStr',label:'chineseName',children:'children'}"/>
        </el-form-item>
        <el-form-item label="排放因子" prop="factorNum" v-if="form.id==null">
          <el-select v-model="form.checkFactor" placeholder="选择排放因子" style="width: 100%" @change="checkFactorFun">
            <el-option class="index-option" v-for="dict in factorItemList" :key="dict['emissions']"
                       :label="dict['emissions']+'【'+dict['unit']+'】'+(dict['type']==1?'上':'下')"
                       :value="dict['emissions']+'_'+dict['type']" />
          </el-select>
        </el-form-item>
        <el-form-item label="排放因子" prop="factorNum">
          <el-input v-model="form.factorNum" placeholder="请输入排放因子" style="width: 60%"/>
          <el-input v-model="form.factorUnit" placeholder="排放单位" style="width: 40%"/>
          <el-form-item label="" prop="factorUnit"/>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="上下游" prop="factorType">
          <el-select v-model="form.factorType" placeholder="请选择上下游" style="width: 100%">
            <el-option class="index-option" v-for="dict in $store.state.factorDict.factorTypeOptions"
                       :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

     <product-carbon-con-sum-his-form ref="ProductCarbonConSumHisFormRef" />
  </div>
</template>

<script>
import { listProductCarbonConsumables, getProductCarbonConsumables, delProductCarbonConsumables, addProductCarbonConsumables, updateProductCarbonConsumables, selectAvgByProductId } from "@/api/carbon/productCarbonConsumables";
import ProductCarbonConSumHisForm from "./ProductCarbonConSumHisForm"
export default {
  name: "ProductCarbonConsumables",
  props:{
    productId: {
      type: Number,
      required: true,
    },
  },
  components:{
    ProductCarbonConSumHisForm
  },
  data() {
    return {
      categorizeCodeArr: [],
      stageOptions: [],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      queryParams: {
        productId: null,
        stageId: null,
        stageIds: [],
        categorizeCode: null,
        name: null,
        quantity: null,
        factorNum: null,
        factorUnit: null,
        factorType: null
      },
      // 产品碳足迹-产品排放行为记录表格数据
      productCarbonConsumablesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      factorItemList: [],

      avgFactorNum:0,
     carbonNum:0,
    };
  },
  created() {
  },
  methods: {
    handleShowHis(row){
      this.$refs.ProductCarbonConSumHisFormRef.handleShow(row);
    },
    checkFactorFun(val){
      for (let item of this.factorItemList){
        if((item['emissions']+'_'+item['type'])===val){
          this.form.factorNum = item['emissions'];
          this.form.factorUnit = item['unit'];
          this.form.factorType = item['type'];
          return
        }
      }
      this.form.factorNum = null;
      this.form.factorUnit = null;
      this.form.factorType = null;
    },
    changeCategorizeCode(list){
      this.queryParams.categorizeCode = list.join(",");
      if(list.length<3){
        this.queryParams.categorizeCode =this.queryParams.categorizeCode+",";
      }
    },
    chickCategorizeCode(list){
      for (let item of this.$store.state.factorDict.categorizeInfoOptions){
        if(item.idStr===list[list.length-1]){
          if(item.factorItemList&&item.factorItemList.length>0){
            this.factorItemList=item.factorItemList;
            this.checkFactorFun(item.factorItemList[0]['emissions']+'_'+item.factorItemList[0]['type'])
          }else {
            this.factorItemList=[];
          }
          return
        }
      }
      this.factorItemList=[];
    },
    checkStageItem(item){
      this.queryParams.productId=item.productId;
      this.queryParams.productCarbonId=item.productCarbonId;
      let stageIds = [item.id];
      let stageOptions = [];
      if(item.type==2){
        stageOptions.push(item);
      }
      if(item.children){
        for (let menu of  item.children){
          stageIds.push(menu.id);
          if(menu.type==2){
            stageOptions.push(menu);
          }
        }
      }
      this.queryParams.stageIds=stageIds;
      this.stageOptions=stageOptions;
      this.getList();
    },
    /** 查询产品碳足迹-产品排放行为记录列表 */
    getList() {
      this.loading = true;
      listProductCarbonConsumables(this.queryParams).then(response => {
        this.calCarbonNum(response.rows);
        this.productCarbonConsumablesList = response.rows;
        this.loading = false;
      });
    },
    selectAvgFun(productId){
      selectAvgByProductId(productId).then(response => {
        if(response.data){
          this.avgFactorNum=response.data
        }else {
          this.avgFactorNum=0;
        }
      });
    },
    calCarbonNum(list){
      if(!list){
        this.carbonNum=0;
        return
      }
      let sum = 0;
      for (let item of list){
        if(item.factorNum&&item.quantity){
          sum =sum+(item.factorNum*item.quantity);
          // item.carbonSum = (item.factorNum*item.quantity)
        // }else {
        //   item.carbonSum = 0
        }
      }
      this.carbonNum=sum.toFixed(2)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productId: this.queryParams.productId,
        productCarbonId: this.queryParams.productCarbonId,
        stageId: null,
        categorizeCode: null,
        quantity: null,
        factorNum: null,
        factorUnit: null,
        name: null,
        factorType: null
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length!==1;
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品碳足迹";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getProductCarbonConsumables(row.id).then(response => {
        this.form = response.data;
        if(response.data.categorizeCode){
          this.categorizeCodeArr = response.data.categorizeCode.split(",");
        }
        this.open = true;
        this.title = "修改产品碳足迹";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if(this.categorizeCodeArr.length>0){
        this.form.categorizeCode = this.categorizeCodeArr.join(",");
      }else {
        this.form.categorizeCode = '';
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProductCarbonConsumables(this.form).then(response => {
              if (response.code === '200') {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addProductCarbonConsumables(this.form).then(response => {
              if (response.code === '200') {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delProductCarbonConsumables(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
  }
};
</script>
